<script setup>
import { Lock, User, EditPen, Message } from '@element-plus/icons-vue'
import router from '@/router'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { post } from '@/net'

const formRef = ref()
const isEmailValid = ref(false)
const coldTime = ref(0)

const form = reactive({
  username: '',
  password: '',
  password_repeat: '',
  email: '',
  code: ''
})
// 校验用户名是否和法
const validateUsername = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else {
    if (!/^[\u4e00-\u9fa5A-Za-z]+$/.test(value)) {
      callback(new Error('用户名不能包含特殊字符，只能是中文/英文'))
    }
    callback()
  }
}

// y
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else {
    if (form.password !== value) {
      callback(new Error('两次密码不一致'))
    }
    callback()
  }
}

const rules = {
  username: [
    { validator: validateUsername, trigger: ['blur', 'change'] },
    { min: 2, max: 8, message: '用户名长度必须在2-8个字符之间', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入秘密', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度必须在6-16个字符之间', trigger: ['blur', 'change'] }
  ],
  password_repeat: [
    { validator: validatePassword, trigger: ['blur', 'change'] },
    { min: 6, max: 16, message: '密码长度必须在6-16个字符之间', trigger: ['blur', 'change'] }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入合法的电子邮箱地址', trigger: ['blur', 'change'] }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const onValidate = (prop, isValid) => {
  if (prop === 'email') isEmailValid.value = isValid
}

const register = () => {
  formRef.value.validate((isValid) => {
    if (!isValid) ElMessage.warning('请完整填写注册表单内容～')
    else {
      post(
        '/api/auth/register',
        {
          username: form.username,
          password: form.password,
          email: form.email,
          code: form.code
        },
        (message) => {
          ElMessage.success(message)
          router.push('/')
        }
      )
    }
  })
}

const validateEmail = () => {
  coldTime.value = 60
  post(
    '/api/auth/valid-register-email',
    {
      email: form.email
    },
    (message) => {
      ElMessage.success(message)
      // 定时器
      setInterval(() => coldTime.value--, 1000)
    },
    (message) => {
      ElMessage.warning(message)
      coldTime.value = 0
    }
  )
}
</script>

<template>
  <div style="text-align: center; margin: 0 20px">
    <div style="margin-top: 100px">
      <div style="font-size: 25px; font-weight: bold">注册行用户</div>
      <div style="font-size: 14px; color: rgb(128, 128, 128)">
        欢迎进入学习平台，请在下方填写相关信息
      </div>
    </div>

    <div style="margin-top: 50px">
      <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
        <el-form-item prop="username">
          <el-input v-model="form.username" type="text" :maxlength="8" placeholder="用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" :maxlength="16" placeholder="密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password_repeat">
          <el-input
            v-model="form.password_repeat"
            type="password"
            :maxlength="16"
            placeholder="请再次确任密码"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="form.email" type="text" placeholder="电子邮箱地址">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          ><el-row :gutter="10" style="width: 100%">
            <el-col :span="17">
              <el-input
                v-model="form.code"
                type="text"
                :maxlength="6"
                placeholder="电子邮箱地址验证码"
              >
                <template #prefix>
                  <el-icon><EditPen /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="7">
              <el-button
                type="success"
                plain
                :disabled="!isEmailValid || coldTime > 0"
                @click="validateEmail"
              >
                {{ coldTime > 0 ? '请稍后' + coldTime + ' 秒' : '获取验证码' }}</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>

    <div style="margin-top: 50px">
      <div>
        <el-button style="width: 270px" type="warning" plain @click="register">立即注册</el-button>
      </div>
      <el-divider>
        <el-link style="font-size: 13px" @click="router.push('/')">已有账号？返回登录 </el-link>
      </el-divider>
    </div>
  </div>
</template>

<style scoped></style>
